package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadDemo1 {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
        //创建MyCallable对象
        Callable<String> myCallable = new MyCallable(100);
        FutureTask<String> futureTask = new FutureTask<>(myCallable);
        //创建Thread进程对象
        Thread thread = new Thread(futureTask,"1号");
        thread.start();


        //创建MyCallable对象
        Callable<String> myCallable1 = new MyCallable(10);
        FutureTask<String> futureTask1 = new FutureTask<>(myCallable1);
        //创建Thread进程对象
        Thread thread1 = new Thread(futureTask1,"2号");
        thread1.start();

        //获取进程结果
        try {
            String s = futureTask.get();
            System.out.println("进程1结果"+s);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String s1 = futureTask1.get();
            System.out.println("进程2结果"+s1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class MyCallable implements Callable<String> {
    private int n;
    public MyCallable(int n) {
        this.n = n;
    }
    @Override
    public String call() throws Exception {
        int num = 0;
        for (int i = 1; i <= n; i++) {
            num += i;
        }
        return Thread.currentThread().getName()+"计算结果为:"+ num;
    }
}
